package iNotes;

import iNotes.assist.DataPool;
import iNotes.assist.Utils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;

@WebServlet(name = "SignUp", value = "/SignUp")
public class SignUp extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        return;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uName = request.getParameter("uname");
        String password = request.getParameter("pwd");
        HttpSession session = request.getSession();

        Connection connection = null;
        CallableStatement callableStatement = null;
        PreparedStatement preparedStatement = null;
        int id = 0;
        try {
            connection = DataPool.ds.getConnection();
            callableStatement = connection.prepareCall("{call checkExist(?,?)}");
            callableStatement.setString(1,uName);
            callableStatement.registerOutParameter(2, Types.INTEGER);
            callableStatement.execute();
            id = callableStatement.getInt(2);
            if (id != 0) {
                session.setAttribute("duplicatedName", "true");
                response.sendRedirect("register.jsp");
            } else {
                try {
                    preparedStatement = connection.prepareStatement("insert into user values(NULL,?,?)");
                    preparedStatement.setString(1, uName);
                    preparedStatement.setString(2, password);
                    preparedStatement.executeUpdate();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                session.setAttribute("duplicatedName", "false");
                session.setAttribute("register","OK");
                response.sendRedirect("index.jsp");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            Utils.close(connection,null,preparedStatement,callableStatement);
        }
    }
}
